import Router from '@koa/router'
import dayjs from 'dayjs'
import { map, pick } from 'lodash'
import {
    eq,
    insert,
    like,
    select,
    delete as sqlDelete,
    update,
} from 'mysql-bricks'
import { query } from '../models'
/**
 * 获取车主列表
 */
export const getOwnerPageController: Router.Middleware = async (ctx) => {
    const likePicked = pick(ctx.query, ['name', 'phone'])
    const likeWhereExp = map(likePicked, (v, k) => like(k, `%${v}%`))
    const eqPicked = pick(ctx.query, ['gender'])
    const eqWhereExp = map(eqPicked, (v, k) => eq(k, v))
    const page = ctx.query.page || 1
    // 生成sql
    const sql = select(
        'owner.*',
        'park_space.id as parkSpaceId',
        'park_space.number as parkSpaceNumber'
    )
        .from('owner')
        .where(...likeWhereExp, ...eqWhereExp)
        .leftJoin('park_space', { parkSpaceId: 'park_space.id' })

        .limit(+ctx.query.limit || 10)
        .offset((+page - 1) * 10)
        .toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql) as any

    // 循环查询车辆信息
    for (let i = 0; i < res.length; i++) {
        const carSql = select().from('car').where('ownerId', res[i].id).toString()
        // 执行carSql
        const carRes = (await query(carSql)) as any
        res[i].cars = carRes
    }

    const total = await query('select count(*) as total from owner')
    // 返回数据
    ctx.body = {
        total: total[0].total,
        rows: res,
    }
}

/**
 * 获取车主下拉框列表
 */
export const getOwnerOptionListController: Router.Middleware = async (ctx) => {
    // 生成sql
    const sql = select('id', 'name').from('owner').toString()
    // 执行sql
    const res = (await query(sql)) as any

    // 返回数据
    ctx.body = res
}

/**
 * 根据id获取车主信息
 */
export const getOwnerByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    // 生成sql
    const ownerSql = select(
        'owner.*',
        'park_space.id as parkSpaceId',
        'park_space.number as parkSpaceNumber',
        'park.id as parkId',
        'park.name as parkName'
    )
        .from('owner')
        .where('owner.id', id)
        .leftJoin('park_space', { parkSpaceId: 'park_space.id' })
        .leftJoin('park', { parkId: 'park.id' })
        .toString()
    console.log(ownerSql)
    // 执行ownerSql
    const res = (await query(ownerSql)) as any
    if (res.length >= 1) {
        const carSql = select().from('car').where('ownerId', id).toString()
        // 执行carSql
        const carRes = (await query(carSql)) as any
        res[0].cars = carRes
    }

    // 返回数据
    ctx.body = res[0]
}

/**
 * 添加车主
 */
export const postOwnerController: Router.Middleware = async (ctx) => {
    // 获取请求参数
    const data = ctx.request.body
    // 生成sql
    const sql = insert().into('owner').values(data).toString()
    // 执行sql
    const res = (await query(sql)) as any
    // 返回数据
    ctx.body = {
        id: res.insertId,
    }
}

/**
 * 修改车主信息
 */
export const putOwnerByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    const data = ctx.request.body
    // 生成sql
    const sql = update('owner', data).where('id', id).toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

/**
 * 删除车主
 */
export const deleteOwnerByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    // 生成sql
    const sql = sqlDelete().from('owner').where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

/**
 * 更新用户到期时间
 */
export const updateOwnerExpireTimeController: Router.Middleware = async (
    ctx
) => {
    const id = +ctx.query.id //用户id
    const currentTime = ctx.query.currentTime.toString() //当前时间
    const day = +ctx.query.day //套餐天数
    // 生成sql
    const sql =
        'SELECT `owner`.expireTime FROM `owner` WHERE `owner`.id = ' + id + ';'
    // 执行sql
    const res = await query(sql)
    const expireTime = res[0].expireTime.toString()
    const dis = dayjs(expireTime).diff(currentTime, 'hour')
    if (dis < 0) {
        //到期时间小于当前时间
        const expireTime1 = dayjs(currentTime).add(day, 'day')
        // 返回数据
        ctx.body = {
            expireTime: expireTime1,
        }
    } else {
        const expireTime2 = dayjs(expireTime).add(day, 'day')
        ctx.body = {
            expireTime: expireTime2,
        }
    }
}
